package com.eascs.admin.classify.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.classify.entity.O2oLoanAbjustType;
import com.eascs.admin.classify.entity.O2oLoanAbjustTypeFlow;
import com.eascs.admin.classify.service.IO2oClassifyService;
import com.eascs.admin.classify.service.O2oClassifySerivce;
import com.eascs.admin.o2o.internal.util.BaseUtils;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.file.FileTypeConstants;
import com.eascs.pay.entity.O2oPayVo;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.AjaxConfirmButton;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.common.vo.WFRequestParam;

@RestController
@RequestMapping("/rclassify")
public class O2oClassifyRestController extends BaseRestController {

	protected final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	O2oClassifySerivce classifySerivce;
	@Autowired
	O2oLoanapplyService o2oLoanapplyService;
	@Reference
	WorkFlowService workFlowService;
	@Autowired
	private BaseUtils baseUtils;

	@RequestMapping("/detail")
	public BaseRestResult<String> detail(String id) {
		O2oLoanAbjustTypeFlow abjustTypeFlow = classifySerivce.queryFlowById(id);
		O2oLoanAbjustType abjustType = classifySerivce.queryById(abjustTypeFlow.getAbjustId());
		String agreeUrl = baseUtils.getApprovalAgreeUrl(id, null, ProcessTemplate.SYSTEM_MODULE_O2O);
		ViewContext.put("agreeUrl", agreeUrl);
		ViewContext.put("entity", abjustType);
		ViewContext.put("abjustTypeFlow", abjustTypeFlow);
		return HtmlRestResult.popHtmlFragment("/classify/detail");
	}

	@RequestMapping("/approval")
	public BaseRestResult<String> approval(O2oPayVo vo) {
		O2oLoanAbjustType abjustType = classifySerivce.queryById(vo.getReferId());
		logger.info("find O2oLoanAbjustType entity :【{}】", abjustType);
		O2oLoanAbjustTypeFlow abjustTypeFlow = null;
		if (null == abjustType) {
			abjustTypeFlow = classifySerivce.queryFlowById(vo.getReferId());
			logger.info("find O2oLoanAbjustTypeFlow entity :【{}】", abjustTypeFlow);
			if (null != abjustTypeFlow) {
				abjustType = classifySerivce.queryById(abjustTypeFlow.getAbjustId());
			}
		} else {
			abjustTypeFlow = new O2oLoanAbjustTypeFlow();
			abjustTypeFlow.setAjustReason(abjustType.getAjustReason());
			abjustTypeFlow.setNewLoanType(abjustType.getNewLoanType());
			abjustTypeFlow.setOldLoanType(abjustType.getOldLoanType());
		}
		String agreeUrl = baseUtils.getApprovalAgreeUrl(vo.getReferId(), null, ProcessTemplate.SYSTEM_MODULE_O2O);
		String approvalUrl = baseUtils.getApprovalUrl(vo.getNodeAuditorId(), ProcessTemplate.SYSTEM_MODULE_O2O);// 审批代办列表详情URL
		ViewContext.put("agreeUrl", agreeUrl);
		ViewContext.put("approvalUrl", approvalUrl);
		ViewContext.put("approvalStatus", vo.getApprovalStatus());
		ViewContext.put("entity", abjustType);
		ViewContext.put("abjustTypeFlow", abjustTypeFlow);
		return HtmlRestResult.popHtmlFragment("/classify/approval");
	}

	@RequestMapping("/querybillcode")
	public BaseRestResult<List<Object[]>> queryBillCode(String billCode) {
		List<Object[]> data = new ArrayList<>();
		if (StringUtil.hasText(billCode)) {
			data = classifySerivce.queryList(billCode);
		}
		return BaseRestResult.buildRestResult(data);
	}

	@RequestMapping("/start")
	public BaseRestResult<String> start(O2oLoanAbjustTypeFlow abjustType) {
		ModelResult<Boolean> modelResult = this.startUp(abjustType);
		if (modelResult.isSuccess() && modelResult.getModel()) {
			return BaseRestResult.info("流程启动成功").andRefresh();
		} else {
			return BaseRestResult.warn(modelResult.getErrMsg());
		}
	}

	@RequestMapping("/save_start")
	public BaseRestResult<String> saveStart(O2oLoanAbjustTypeFlow abjustTypeFlow, String startType) {
		if (StringUtil.isBlank(abjustTypeFlow.getNewLoanType())) {
			return BaseRestResult.warn("调整状态不能为空");
		}
		if (StringUtil.isBlank(abjustTypeFlow.getAjustReason())) {
			return BaseRestResult.warn("调整原因不能为空");
		}
		// if(checkFile(abjustType)){
		// return BaseRestResult.warn("请上传文件");
		// }
		Date date = new Date();
		User user = null;
		if (null == UserHolder.getUser()) {
			user = new User();
			user.setNo("1");
			user.setCname("系统管理员");
		} else {
			user = UserHolder.getUser();
		}

		O2oLoanAbjustType loanAbjustType = classifySerivce.queryById(abjustTypeFlow.getAbjustId());
		O2oLoanAbjustTypeFlow o2oLoanAbjustTypeFlow = classifySerivce.queryFlowCById(abjustTypeFlow.getAbjustId());
		if (null != o2oLoanAbjustTypeFlow && !o2oLoanAbjustTypeFlow.getFlowStatus().equals(StatusContexts.O2O_NEW)) {
			return BaseRestResult.warn("该单号有一个流程，不能重复提交！");
		}
		o2oLoanAbjustTypeFlow.setNewLoanType(abjustTypeFlow.getNewLoanType());
		o2oLoanAbjustTypeFlow.setAjustReason(abjustTypeFlow.getAjustReason());
//		loanAbjustType.setAjustReason(abjustTypeFlow.getAjustReason());
		// loanAbjustType.setOldLoanType(loanAbjustType.getNewLoanType());
//		loanAbjustType.setNewLoanType(abjustTypeFlow.getNewLoanType());
//		loanAbjustType.setFlowStatus(StatusContexts.O2O_NEW);
		loanAbjustType.setDataType("MA");// 自动改变类型
		loanAbjustType.setUpdateTime(date);
		int i = classifySerivce.updateFlow(o2oLoanAbjustTypeFlow);
		classifySerivce.update(loanAbjustType);
		if (startType.equals("saveStart")) {
			if (i > 0) {
				ModelResult<Boolean> modelResult = this.startUp(o2oLoanAbjustTypeFlow);
				if (modelResult.isSuccess() && modelResult.getModel()) {
					return BaseRestResult.info("保存并启动成功").andRedirect("/classify/ma");
				} else {
					return BaseRestResult.warn(modelResult.getErrMsg());
				}
			}
		} else {
			if (i > 0) {
				return BaseRestResult.info("保存成功").andRedirect("/classify/ma");
			}
		}
		return BaseRestResult.warn("保存失败");
	}

	public ModelResult<Boolean> startUp(O2oLoanAbjustTypeFlow abjustType) {
		O2oLoanAbjustTypeFlow loanAbjustFlowType = classifySerivce.queryFlowById(abjustType.getId());
		O2oLoanAbjustType loanAbjustType = classifySerivce.queryById(loanAbjustFlowType.getAbjustId());
		WFRequestParam param = new WFRequestParam();
		param.setReferId(loanAbjustFlowType.getId());
		param.setReferCode(loanAbjustType.getBillCode());
		param.setReferUrl("/rclassify/approval");
		param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
		param.setProcessType("LOAN_TYPE");
		param.setProcessVersion("v1");
		User user = UserHolder.getUser();
		param.setAppliedby(user.getNo());
		param.setAppliedbyName(user.getCname());
		param.setOrgNo(loanAbjustType.getLtd());
		param.setAppliedDes("借款人：" + loanAbjustType.getLoanUserName() + ", 调整状态：" + getLoanTypeName(loanAbjustFlowType.getNewLoanType()));
		logger.info("启动贷款分类申请，id：【{}】，编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】", loanAbjustFlowType.getId(), loanAbjustType.getBillCode(), ProcessTemplate.SYSTEM_MODULE_O2O, param.getProcessType(), loanAbjustType.getLtd());
		ModelResult<Boolean> modelResult = workFlowService.instance(param);
		if (modelResult.isSuccess() && modelResult.getModel()) {
			Date date = new Date();
			loanAbjustFlowType.setFlowStartTime(date);
			loanAbjustFlowType.setFlowStatus(StatusContexts.O2O_BANK_RUN);
			// loanAbjustFlowType.setUpdateTime(date);
			classifySerivce.updateFlow(loanAbjustFlowType);
		} else {
			logger.error("启动贷款分类申请，id：【{}】，错误信息{}", abjustType.getId(), modelResult.getErrMsg());
		}
		return modelResult;
	}

	@RequestMapping("/loadfile")
	public BaseRestResult<String> classifyFileView(String id, String type) {
		if ("detail".equals(type)) {
			queryDataList(id, FileTypeConstants.CLASSIFY_TYPE, "detail");
		} else {
			queryDataList(id, FileTypeConstants.CLASSIFY_TYPE, null);
		}
		ViewContext.put("type", type);
		ViewContext.put("id", id);
		return new HtmlRestResult("classify/classify_file");
	}

	public String getLoanTypeName(String typeCode) {
		if (typeCode.equals("BAD_LOAN")) {
			return "不良贷款";
		} else if (typeCode.equals("FOLLOW_LOAN")) {
			return "关注贷款";
		} else {
			return "正常贷款";
		}
	}

	/**
	 * 附件列表
	 * 
	 * @param loanapplyNo
	 * @param code
	 * @param detailFlag
	 */
	public void queryDataList(String loanapplyNo, String code, String detailFlag) {
		PageResult<Object[]> pageResult = o2oLoanapplyService.findO2oDataListEntityById(loanapplyNo, "'" + code + "'");
		String titles[] = { "附件类型", "文件名", "提交人", "提交时间", "更新时间" };
		Button[] titleButtons = new Button[] { null, ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles);
		if (!"detail".equals(detailFlag)) {
			AjaxConfirmButton[] dealButton = null;
			dealButton = new AjaxConfirmButton[] { new AjaxConfirmButton("删除 ", "/loanrest/delete/") };
			paginationInfo.setMoreButtons(dealButton);
		}
		paginationInfo.setTitleButtons(titleButtons);
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(1);
		paginationInfo.setBuildRowNumber(true);
		ViewContext.put("pageResult", paginationInfo);// 个人附件
	}

	public boolean checkFile(O2oLoanAbjustType abjustType) {
		PageResult<Object[]> pageResult = o2oLoanapplyService.findO2oDataListEntityById(abjustType.getId(), "'" + FileTypeConstants.CLASSIFY_TYPE + "'");
		if (null != pageResult.getData() && pageResult.getData().size() > 0) {
			return false;
		} else {
			return true;
		}
	}

	@RequestMapping("/delete")
	public BaseRestResult<String> delete(String id) {
		return BaseRestResult.confirm("删除数据不可恢复，确认删除？").andActionAjaxLoad("/rclassify/delete_update?id=" + id);
	}

	@RequestMapping("/delete_update")
	public BaseRestResult<String> delete_update(String id) {
		O2oLoanAbjustTypeFlow abjustTypeFlow = classifySerivce.queryFlowById(id);
		O2oLoanAbjustType loanAbjustType = classifySerivce.queryById(abjustTypeFlow.getAbjustId());
		loanAbjustType.setIsDelete(StatusContexts.O2O_NO);
		loanAbjustType.setDataType("AU");
		loanAbjustType.setFlowStatus("");
		abjustTypeFlow.setIsDelete(StatusContexts.O2O_YES);
		int i = classifySerivce.update(loanAbjustType);
		if (i > 0) {
			classifySerivce.updateFlow(abjustTypeFlow);
			return BaseRestResult.info("删除成功").andRefresh();
		} else {
			return BaseRestResult.warn("删除失败");
		}
	}

	@Reference
	IO2oClassifyService iClassisyService;

	@RequestMapping("/test-123")
	public BaseRestResult<String> test() {
		iClassisyService.insertAU(new O2oLoanAbjustType());
		return BaseRestResult.info("成功");
	}

	@RequestMapping("/init_data")
	public BaseRestResult<String> init_data() {
		List<O2oLoanAbjustType> abjusts = classifySerivce.queryMAList();
		if (null != abjusts && abjusts.size() > 0) {
			for (O2oLoanAbjustType abjustType : abjusts) {
				O2oLoanAbjustTypeFlow loanAbjustFlowType = new O2oLoanAbjustTypeFlow();
				loanAbjustFlowType.setAbjustId(abjustType.getId());
				loanAbjustFlowType.setAjustReason(abjustType.getAjustReason());
				loanAbjustFlowType.setCreateUserName(abjustType.getCreateUserName());
				loanAbjustFlowType.setCreateUserNo(abjustType.getCreateUserId());
				loanAbjustFlowType.setFlowStatus(abjustType.getFlowStatus());
				loanAbjustFlowType.setFlowEndTime(abjustType.getFlowEndTime());
				loanAbjustFlowType.setFlowStartTime(abjustType.getFlowStartTime());
				loanAbjustFlowType.setIsDelete(abjustType.getIsDelete());
				loanAbjustFlowType.setIsNew(StatusContexts.O2O_YES);
				loanAbjustFlowType.setNewLoanType(abjustType.getNewLoanType());
				loanAbjustFlowType.setOldLoanType(abjustType.getOldLoanType());
				classifySerivce.insertFlow(loanAbjustFlowType);
			}
		}
		return BaseRestResult.info("成功");
	}

}
